<?php

class CFeature extends Zend_Db_Table{
	
	protected $_name;
	
	protected $_primary;

	public function __construct(){
		
		$this->_name=R_PRE."features";
		
		$this->_primary="featureid";
		
		parent::__construct();
		
	}

	public function createFeature($data){
		
		$featureid=$this->insert($data);
		
		return $featureid;
		
	}
	
	public function getFeatureCounts($fieldArray=null){
		
		$db=$this->getAdapter();
		
		$select=$db->select();
		
		$select->from($this->_name,'COUNT(*)');
		
		if($fieldArray!=null){
		
			foreach ($fieldArray as $field => $value){
				
				$where = $db->quoteInto("$field = ?", $value);
				
				$select->where($where);
				
			}
		
		}
		
		return $db->fetchOne($select);
		
	}
	
	public function getAllFeatures($from,$counts,$fieldArray=null){
		
		$db=$this->getAdapter();
		
		$select=$db->select();
		
		$select->from($this->_name,'*');
		
		if($fieldArray!=null){
			
			foreach ($fieldArray as $field => $value){
				
				$where = $db->quoteInto("$field = ?", $value);
				
				$select->where($where);
				
			}
			
		}
		
		$select->joinLeft(R_PRE.'productfls', $this->_name.".flid = ".R_PRE."productfls.flid", '*');
		
		$select->order("featureid DESC");
		
		if($counts!=0){
			
			$select->limit($counts, $from);
			
		}
		
		return $db->fetchAll($select);
		
	}
	
	public function editFeature($featureid,$data){
		
		$db=$this->getAdapter();
		
		$where = $db->quoteInto('featureid = ?', $featureid);
		
		$rows_affected=$db->update($this->_name,$data,$where);
		
		if($rows_affected!=1){
			
			return false;
			
		}else{
			
			return true;
			
		}
		
		
	}
	
	public function getDetail($featureid){
		
		$db=$this->getAdapter();
		
		$select = $db->select();
		
		$select->from($this->_name,'*');
		
		$select->where('featureid = ? ',$featureid);
		
		return $db->fetchAll($select);
		
	}
	
	public function delFeatures($featureidArray){
		
		$db=$this->getAdapter();
		
		$featureidString=join(',',$featureidArray);
		
		$result=$db->query("SELECT cut_url FROM $this->_name WHERE featureid IN ($featureidString)");
		
		$array=$result->fetchAll();

		$path=new CPath();
		
		foreach ($array as $value){
			
			@unlink($path->toAbsoluteRootPath($value['cut_url']));
			
		}
		
		$result=$db->query("DELETE FROM $this->_name WHERE featureid IN ($featureidString)");
		
		return $result;
		
	}
	
	public function getFeatureProducts(){
		
		$db=$this->getAdapter();
		
		$result=$db->query("SELECT A.*,".R_PRE."items.subject
							FROM ".R_PRE."items,(
							SELECT $this->_name.*,B.itemid
							FROM $this->_name  
							LEFT JOIN ".R_PRE."products AS B ON $this->_name.featureid = B.featureid 
							)AS A 
							WHERE A.itemid=".R_PRE."items.itemid 
							ORDER BY A.featureid DESC 
							"
							);

		
		$array=$result->fetchAll();
		
		return $array;
		
	}
	

	
}